package main

import (
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type Ele struct {
	ID      bson.ObjectId `bson:"_id,omitempty" json:"id"`
	Name    string        `bson:"name" json:"name"`
	Type    string        `bson:"type" json:"type"`
	Status  int           `bson:"status" json:"status"`
	Content string        `bson:"content" json:"content"`
	BookId  bson.ObjectId `bson:"bookId" json:"bookId"`
}

func eleCollection() *mgo.Collection {
	return GetSession().DB("mybook").C("eles")
}

// 创建Ele
func CreateEle(ele *Ele) error {
	return eleCollection().Insert(ele)
}

// 获取单个Ele
func GetEle(id string) (*Ele, error) {
	if !bson.IsObjectIdHex(id) {
		return nil, mgo.ErrNotFound
	}

	var ele Ele
	err := eleCollection().FindId(bson.ObjectIdHex(id)).One(&ele)
	return &ele, err
}

// 更新Ele
func UpdateEle(id string, updateData bson.M) error {
	if !bson.IsObjectIdHex(id) {
		return mgo.ErrNotFound
	}
	return eleCollection().UpdateId(bson.ObjectIdHex(id), bson.M{"$set": updateData})
}

// 删除Ele
func DeleteEle(id string) error {
	if !bson.IsObjectIdHex(id) {
		return mgo.ErrNotFound
	}
	return eleCollection().RemoveId(bson.ObjectIdHex(id))
}

// 删除书籍的所有Ele
func DeleteElesByBook(bookID string) error {
	if !bson.IsObjectIdHex(bookID) {
		return mgo.ErrNotFound
	}
	return eleCollection().Remove(bson.M{"bookId": bson.ObjectIdHex(bookID)})
}

// 分页获取书籍的所有Ele
func GetElesByBook(bookID string, page, pageSize int) ([]Ele, error) {
	if !bson.IsObjectIdHex(bookID) {
		return nil, mgo.ErrNotFound
	}

	var eles []Ele
	skip := (page - 1) * pageSize
	err := eleCollection().Find(bson.M{"bookId": bson.ObjectIdHex(bookID)}).
		Skip(skip).
		Limit(pageSize).
		All(&eles)
	return eles, err
}

// 获取书籍的Ele总数
func GetElesCountByBook(bookID string) (int, error) {
	if !bson.IsObjectIdHex(bookID) {
		return 0, mgo.ErrNotFound
	}

	count, err := eleCollection().Find(bson.M{"bookId": bson.ObjectIdHex(bookID)}).Count()
	return count, err
}

// search ele
func SearchEles(data Ele) ([]Ele, error) {
	var eles []Ele
	m, err := StructToBSONM(data)
	if err != nil {
		return nil, err
	}
	//按type分类排序
	err = eleCollection().Find(m).All(&eles)
	return eles, err
}

// 插入数组ele到数据库中，如果数组为空，则不插入
func InsertEles(eles []Ele) error {
	if len(eles) == 0 {
		return nil
	}
	// 将 []Ele 转换为 []interface{}
	interfaceSlice := make([]interface{}, len(eles))
	for i, v := range eles {
		interfaceSlice[i] = v
	}
	return eleCollection().Insert(interfaceSlice...)
}
